#define _CRT_SECURE_NO_WARNINGS
#include"SeqList.h"

void SeqListInit(SeqList* ps)
{
	ps->a = (SLDataType*)malloc(sizeof(SLDataType)*4);
	if (ps->a == NULL)
	{
		perror("malloc fail");
		return;
	}
	ps->sz = 0;
	ps->capacity = 4;
}

void SeqListDestroy(SeqList* ps)
{
	free(ps->a);
	ps->a = NULL;
	ps->sz = 0;
	ps->capacity = 0;
}

void SeqListPrint(const SeqList* ps)
{
	int i = 0;
	for (i = 0; i < ps->sz; i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}
void SLCheckCapacity(SeqList* ps)
{
	assert(ps);
	if (ps->sz == ps->capacity)
	{
		SLDataType* p = (SLDataType*)realloc(ps->a ,sizeof(SLDataType) * ps->capacity*2);
		if (p == NULL)
		{
			perror("CheckCapacity ,fail");
			return;
		}
		ps->a = p;
		ps->capacity *= 2;
	}
}
void SeqListPushBack(SeqList* ps, SLDataType x)
{
	SLCheckCapacity(ps);
	ps->a[ps->sz++] = x;
}

void SeqListPushFront(SeqList* ps, SLDataType x)
{
	SLCheckCapacity(ps);
	for (int i = ps->sz; i > 0; --i)
	{
		ps->a[i] = ps->a[i - 1];
	}
	ps->a[0] = x;
	ps->sz++;
}

void SeqListPopFront(SeqList* ps)
{
	assert(ps);
	int i = 0;
	for (i = 0; i < ps->sz; i++)
	{
		ps->a[i] = ps->a[i + 1];
	}
	ps->sz--;
}

void SeqListPopBack(SeqList* ps)
{
	assert(ps->sz);
	ps->sz--;
}

int SeqListFind(SeqList* ps,SLDataType x)
{
	int i;
	for (i = 0; i < ps->sz; i++)
	{
		if (ps->a[i] == x)
		{
			return i;
		}
	}
	return -1;
}

void SeqListInsert(SeqList* ps, int pos, SLDataType x)
{
	assert(ps);
	assert(pos >= 0&&pos <= ps->sz);
	SLCheckCapacity(ps);
	int i = 0;
	int end = ps->sz;
	for(i = end; i > pos; i--)
	{
		ps->a[i] = ps->a[i-1];
	}
	ps->a[pos] = x;
	ps->sz++;
}

void SeqListErase(SeqList* ps, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->sz);
	int i = 0;
	for (i = pos; i < ps->sz; i++)
	{
		ps->a[i] = ps->a[i + 1];
	}
	ps->sz--;
}

void SeqListChange(SeqList* ps, int pos, SLDataType x)
{
	ps->a[pos] = x;
}